﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Diagnostics;
using ProgNetComponents.Data.SqlCe;
using ProgNetComponentsDx.Browsers;
using System.IO;
using ProgNetComponentsDx.Options;
using BuildHelper.Setup.Brancze;
using ProgNetComponents.Classes;
using BuildHelper.Scheduler;

namespace BuildHelper.Work.JAVA
{
    public static class BudowanieJavyTools
    {
        public const string INFO_KONIEC_BUDOWANIA = "Koniec budowania";
        public const string INFO_POCZATEK_BUDOWANIA = "Poczatek budowania";
        public const string INFO_KONIEC_DEPLOYOWANIA = "Koniec deployowania";
        public const string INFO_POCZATEK_DEPLOYOWANIA = "Poczatek deployowania";
        public const string INFO_RESTART_SRV = "Restart Servera";

        public static void ReadBranch(string brancz, JavaDataSet javaDataSet)
        {
            BranczeDataSet branczeDataSet1 = new BranczeDataSet();
            branczeDataSet1.STP_BRANCZE.Clear();
            javaDataSet.Clear();
            SqlCeDataManager sqlCeDataManager1 = new SqlCeDataManager();
            sqlCeDataManager1.AutoLogExceptions = true;
            sqlCeDataManager1.AddTableDef(branczeDataSet1.STP_BRANCZE_APPS, "SELECT A.* FROM STP_BRANCZE_APPS A, STP_APPS B WHERE  A.STP_BR_APP_APP = B.STP_APP_KOD and B.STP_APP_IS_JAVA = 1 AND STP_BR_APP_BRANCZ = @BRANCZ ORDER BY STP_BR_APP_POZYCJA ASC");

            bool res = sqlCeDataManager1.FillTable(branczeDataSet1.STP_BRANCZE_APPS, new NamedObject("@BRANCZ", brancz));
            DataRow javaSysRow;
            string sys;
            foreach (DataRow rowStm in branczeDataSet1.STP_BRANCZE_APPS)
            {
                sys = rowStm["STP_BR_APP_APP"].AsString();
                javaSysRow = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Setup.Apps, sys);
                if (javaSysRow != null && javaSysRow["STP_APP_JAVA_NAME"].IsNotNull() && javaSysRow["STP_APP_IS_JAVA"].AsBool())
                {
                    var r = javaDataSet.BUILD.AddBUILDRow(sys, true, true, string.Empty, false, false);
                }
            }
            if (javaDataSet.GCM_SETTINGS.Rows.Count == 0)
            {
                var r = javaDataSet.GCM_SETTINGS.NewRow();
                javaDataSet.GCM_SETTINGS.Rows.Add(r);
            }
            sqlCeDataManager1.Dispose();
        }
        public static bool ReadTemplate(JavaDataSet ds, string template)
        {
            bool result = false;
            SqlCeDataManager m = null;
            try
            {
                m = new SqlCeDataManager();
                m.AutoLogExceptions = true;
                string nazwa = template;
                NamedObject parameter = new NamedObject();
                parameter.Name = "@NAZWA";
                parameter.Value = nazwa;
                byte[] bytes = m.ExecuteScalar("SELECT STP_TMP_XML FROM STP_TEMPLATES WHERE STP_TMP_GRUPA =\'JAVA\' AND STP_TMP_NAZWA = @NAZWA", parameter) as byte[];
                string xml = bytes.ByteArrayToString();
                ds.ReadXmlString(xml);
                if (ds.GCM_SETTINGS.Rows.Count == 0)
                {
                    var r = ds.GCM_SETTINGS.NewRow();
                    ds.GCM_SETTINGS.Rows.Add(r);
                }
                result = true;
            }
            catch (Exception ex)
            {
                ex.Log();
            }
            finally
            {
                if (m != null)
                    m.Dispose();
            }
            return result;
        }
        public static void ApplyTemplate(JavaDataSet javaDataSet1, DataSet TemplateDataSet)
        {
            DataRow t;
            foreach (var r in javaDataSet1.BUILD)
            {
                t = TemplateDataSet.Tables["BUILD"].SelectFirstRow("STM = " + r["STM"].AsString().EscapeSql());
                r.Buduj = t.GetColumnValue("Buduj", false);
                r.Pakuj = t.GetColumnValue("Pakuj", false);
                r.Klasy = t.GetColumnValue("Klasy", string.Empty);
                r.GENERATED = t.GetColumnValue("GENERATED", false);
                r.PackWS = t.GetColumnValue("PackWS", false);
            }
            DataRow row = null;
            if (javaDataSet1.GCM_SETTINGS.Rows.Count == 0)
            {
                row = javaDataSet1.GCM_SETTINGS.NewRow();
                javaDataSet1.GCM_SETTINGS.Rows.Add(row);
            }
            else
            {
                row = javaDataSet1.GCM_SETTINGS.Rows[0];
            }
            t = null;
            if (TemplateDataSet.Tables.Contains("GCM_SETTINGS") &&
                TemplateDataSet.Tables["GCM_SETTINGS"].Rows.Count > 0)
                t = TemplateDataSet.Tables["GCM_SETTINGS"].Rows[0];
            foreach (DataColumn c in javaDataSet1.GCM_SETTINGS.Columns)
            {
                row[c] = t.GetColumnValue(c.ColumnName, false);
            }
        }
       
        public static void BuildPack(Process pBuildPack, JavaDataSet ds, bool clean, string brancz, int serwer, bool deploy, bool updateBuildXml)
        {
            SqlCeDataManager m = GlobalTools.CreateManager();
            string path = m.ExecuteScalar("SELECT STP_BR_KATALOG FROM STP_BRANCZE WHERE STP_BR_NAZWA = " + brancz.EscapeSql()).AsString();
            if (path.IsNotNull())
            {
                string gene = path.TrimEnd('\\') + @"\nd_src\gene";
                pBuildPack.CdDir(gene);
                if (updateBuildXml)
                    UpdateBuildXml(ds, brancz);
                CreateBuildPackProperties(ds, path, serwer);
                pBuildPack.Execute("echo " + INFO_POCZATEK_BUDOWANIA);

                pBuildPack.EchoOff();
                pBuildPack.CdDir(gene);
                GlobalTools.ProcessTools.SetEnvVariable(pBuildPack, brancz);
                if (clean)
                {
                    pBuildPack.Execute("call ant clean");
                    pBuildPack.Execute("call ant cleanModules");
                }
                pBuildPack.Execute("call ant build");
                pBuildPack.Execute("call ant packInstance");

                if (deploy)
                    DeployEar(pBuildPack, serwer, gene, brancz);
               
                pBuildPack.Execute("echo " + INFO_KONIEC_BUDOWANIA);

            }

            m.Dispose();
        }

        const string BuildXmlFile = @"{branch}\nd_src\gene\apps\{stm}\src\ws\wsjava\build.xml";
        const string maskSrcNormal = "(\\s*)(<src path=\"\\$\\{src\\.dir\\}\"/>\\s*)";
        const string maskGenerated = "(\\s*)(<src path=\"\\$\\{generated\\.dir\\}\"/>\\s*)";
        const string maskSrcAdditional = "(\\s*)<src path=\"\\$\\{src\\.dir\\}/[^>]*>\\s*";
        static string dependensyMask = "(<target name=\"compile\" depends=\")([^\"]*)";
        static string maskGCMUNITTEST = "(target name=\"packGcmWebService\" depends=\")([^\"]*)";

        public static void ClearBuildXmls(string brancz)
        {
            if (brancz.IsNull())
                brancz = BranczeTools.ActiveBranch;
            JavaDataSet ds = new JavaDataSet();
            ReadBranch(brancz, ds);
            List<JavaDataSet.BUILDRow> rows = new List<JavaDataSet.BUILDRow>();
            foreach (var r in ds.BUILD)
            {
                rows.Add(r);
            }
            using (SqlCeDataManager m = GlobalTools.CreateManager())
            {
                string path = m.ExecuteScalar("SELECT STP_BR_KATALOG FROM STP_BRANCZE WHERE STP_BR_NAZWA = " + brancz.EscapeSql()).AsString().TrimEnd('\\');
                ClearBuildXmls(path, rows);
            }
        }
        private static void ClearBuildXmls(string path, List<JavaDataSet.BUILDRow> rows)
        {
            //return;
            if (path.IsNotNull())
            {
                string buildXmlReal;
                string stm;
                Process svn = GlobalTools.CreateCMDProcess(null);
                GlobalTools.TortoiseTools.AddSvnToPath(svn);
                foreach (DataRow r in rows)
                {
                    stm = r["STM"].AsString();
                    buildXmlReal = BuildXmlFile.Replace("{branch}", path).Replace("{stm}", stm);
                    svn.Execute("svn revert " + buildXmlReal);
                }
                svn.CallExit();
                svn.SafeWaitForExit();
                svn.Dispose();
            }
        }
        private static bool UpdateDependensyValue(string mask, ref string content, List<string> strings)
        {
            string orgValue = content.GetFirstMatch(mask, 2);
            string newValue = orgValue;
            foreach (string s in strings)
                newValue = newValue.Replace(s, "");
            newValue = newValue.Trim(',');
            newValue = newValue.XReplace(",+", ",");
            bool changed = false;
            if (orgValue != newValue)
            {
                content = content.XReplace(mask, "$1" + newValue);
                changed = true;
            }
            return changed;
        }
        private static bool RemoveTask(string task, ref string content)
        {
            content = content.XReplace("(\\s*)<antcall target=\"" + task + "\"\\s*/>", "");
            return true;
        }
        public static void UpdateBuildXml(JavaDataSet ds, string brancz)
        {
            List<JavaDataSet.BUILDRow> rows = new List<JavaDataSet.BUILDRow>();
            foreach(var r in ds.BUILD)
            {
                if (!r.IsBudujNull() && r.Buduj)
                {
                    rows.Add(r);
                }
            }
            
            if (rows.Count > 0)
            {
                if (brancz.IsNull())
                    brancz = BranczeTools.ActiveBranch;
                using (SqlCeDataManager m = GlobalTools.CreateManager())
                {
                    string path = m.ExecuteScalar("SELECT STP_BR_KATALOG FROM STP_BRANCZE WHERE STP_BR_NAZWA = " + brancz.EscapeSql()).AsString().TrimEnd('\\');
                    if (path.IsNotNull())
                    {
                        string buildXmlReal;
                        string stm;
                        string content;
                       
                        ClearBuildXmls(path, rows);
                        List<string> strings = new List<string>();
                        foreach (var r in rows)
                        {
                            stm = r.STM.AsString();
                            buildXmlReal = BuildXmlFile.Replace("{branch}", path).Replace("{stm}", stm);
                            string klasy = (r.IsKlasyNull() ? string.Empty : r.Klasy);
                            string newMask;
                            bool changed = false;
                           
                            try
                            {
                                if (File.Exists(buildXmlReal))
                                { 
                                    content = buildXmlReal.ReadFile();
                                    strings.Clear();
                                    if (stm == "GCM")
                                    {
                                        if (ds.GCM_SETTINGS.Rows.Count == 1)
                                        {
                                            var gcmRow = ds.GCM_SETTINGS[0];
                                            if (gcmRow.runHbm2Java)
                                                strings.Add("runHbm2Java");
                                            if (gcmRow.wsdl2java)
                                                strings.Add("wsdl2java");
                                            if (strings.Count > 0)
                                                changed |= UpdateDependensyValue(dependensyMask, ref content, strings);

                                            if (gcmRow.gcmUnitTest.AsBool())
                                            {
                                                strings.Clear();
                                                strings.Add("gcmUnitTest");
                                                changed |= UpdateDependensyValue(maskGCMUNITTEST, ref content, strings);
                                            }
                                            DataColumn[] taskCols = {
                                                                    ds.GCM_SETTINGS.copyCorbaLibColumn,
                                                                    ds.GCM_SETTINGS.copyFilesColumn,
                                                                    ds.GCM_SETTINGS.createPropertyFilesColumn,
                                                                    ds.GCM_SETTINGS.packElectricCfgColumn,
                                                                    ds.GCM_SETTINGS.packGcmAntToolsColumn,
                                                                    ds.GCM_SETTINGS.packGcmApiJarColumn,
                                                                    ds.GCM_SETTINGS.packGcmEjbJarColumn,
                                                                    ds.GCM_SETTINGS.packIntegrationEjbJarColumn,
                                                                    ds.GCM_SETTINGS.prepareWsdlsColumn};
                                            foreach (DataColumn c in taskCols)
                                            {
                                                if (gcmRow[c].AsBool())
                                                    changed |= RemoveTask(c.ColumnName, ref content);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (r.PackWS)
                                        {
                                            changed |= RemoveTask("pack" + stm + "packBioWebService", ref content);
                                        }
                                    }
                                    

                                    if (klasy.IsNotNull())
                                    {
                                        List<string> list = klasy.ToLines();
                                        if (list != null && list.Count > 0)
                                        {
                                            newMask = string.Empty;
                                            foreach (string s in list)
                                            {
                                                newMask += "$1<src path=\"${src.dir}/" + s.TrimStart('/', '\\') + "\"/>";
                                            }
                                            newMask += "$1";
                                            content = content.XReplace(maskSrcNormal, newMask, System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Multiline);
                                            changed = true;
                                        }
                                    }
                                    if (r["GENERATED"].AsBool())
                                    {
                                        content = content = content.XReplace(maskGenerated, "", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Multiline);
                                        changed = true;
                                    }
                                    
                                    if (changed)
                                        content.Trim().WriteToFile(buildXmlReal);
                                }
                            }
                            catch { }
                        }
                    }
                }
            }
        }
        public static void DeployEar(Process process, int serwer, string gene, string brancz)
        {
            process.Execute("echo " + INFO_POCZATEK_DEPLOYOWANIA);
            string distSrv = gene.TrimEnd('\\') + @"\dist\server\";
            SqlCeDataManager m = GlobalTools.CreateManager();
            Setup.Serwery.SeweryDataSet.STP_SERWERYDataTable dt = new Setup.Serwery.SeweryDataSet.STP_SERWERYDataTable();
            m.AddTableDef(dt, "SELECT * FROM STP_SERWERY  WHERE STP_SRW_ID = " + serwer);
            m.FillTable(dt);

            DataRow srvRow = dt.SelectFirstRow();
            bool updateData = true;
            if (srvRow != null)
            {
                string typ = srvRow["STP_SRW_TYP"].AsString();
                distSrv = distSrv + typ;
                string instancja = srvRow["STP_SRW_INSTANCJA"].AsString();
                
                switch (typ)
                {
                    case GlobalTools.ServerTools.ServerType.JBoss4:
                    case GlobalTools.ServerTools.ServerType.JBoss5:
                        if(instancja.IsNull())
                            instancja = "default";
                        string distDir = srvRow["STP_SRW_DIR"].AsString().TrimEnd('\\') + "\\server\\"+instancja+"\\deploy";
                        process.CdDir(distDir);
                        process.Execute("del /F /Q *.ear");
                        process.Execute("copy /Y " + (distSrv + "\\*.ear").AddDoubleQuotes() + " " + distDir.AddDoubleQuotes());
                        process.Echo(INFO_RESTART_SRV + " " + serwer);
                        break;
                    case GlobalTools.ServerTools.ServerType.OAS:
                        string userName = srvRow["STP_SRW_LOGIN"].AsString();
                        string pass = srvRow["STP_SRW_HASLO"].AsString();
                        string file = "%ear_file%";
                        string name = srvRow["STP_SRW_DEPLOY_NAZWA"].AsString();
                        process.Execute("for /f \"tokens=1\" %i IN ('dir /b "+(distSrv+"\\*.ear").AddDoubleQuotes() +"') do set ear_file=%i");
                        string str = @"java -jar admin_client.jar deployer:oc4j:localhost " +
                            userName + " " + pass + " -deploy  -file " + (distSrv+"\\"+file).AddDoubleQuotes() + " -deploymentName " + name + " -bindAllWebApps";
                        string katalogSerwera = srvRow["STP_SRW_DIR"].AsString().TrimEnd('\\') + @"\j2ee\home";
                        process.CdDir(katalogSerwera);
                        process.Execute(str);
                        break;
                    default :
                        updateData = false;
                        process.Echo(GlobalTools.Messages.MSG_INFO + " Server " + typ + " nie jest wspierany.");
                        break;
                }
                if (updateData)
                    srvRow["STP_SRW_LAST_BR"] = brancz;

            }
            if (updateData)
            {
                m.UpdateTable(dt);
                BrowserCache.RefreshCacheForTable("STP_SERWERY");
            }
            m.Dispose();
            process.Execute("echo " + INFO_KONIEC_DEPLOYOWANIA);
        }

        private static int BudujId;
        private class BudujProcInfo
        {
            public string Id
            {
                get;
                set;
            }
            public bool StopOnError
            {
                get;
                set;
            }
            public string Brancz { get; set; }
            public string LogFile { get; set; }
            public bool ShowInfo { get; set; }
            public DataRow Row
            {
                get;
                set;
            }
            public bool Error
            {
                get;
                set;
            }

            private List<string> buildStm = new List<string>();
            private List<string> packStm = new List<string>();
            int buildStmIdx = 0;
            int packStmIdx = 0;
            public void SetDataSet(JavaDataSet javaDataSet)
            {
                DataRow[] rows = javaDataSet.BUILD.Select();
                foreach (DataRow r in rows)
                {
                    if (r["STM"].AsString() != "GENESDK")
                    {
                        if (r["Buduj"].AsBool())
                            buildStm.Add(r["STM"].AsString());
                        if (r["Pakuj"].AsBool())
                            packStm.Add(r["STM"].AsString());
                    }
                }
            }
            private string CompileStm
            {
                get;
                set;
            }
            private string PackStm
            {
                get;
                set;
            }
            private string CurCommand
            {
                get;
                set;
            }

            private void SetProgressText()
            {
                string text = "";
                //if (buildStm.Count > 0 && buildStmIdx > 0)
                {
                    text = "Kompilacja: " + buildStmIdx + "/" + buildStm.Count;
                    if (CompileStm.IsNotNull())
                        text += " (" + CompileStm + ")";
                }
                //if (packStm.Count > 0 && packStmIdx > 0)
                {
                    text += "; Pakowanie: " + packStmIdx + "/" + packStm.Count;
                    if (PackStm.IsNotNull())
                        text += " (" + PackStm + ")";
                }
                if (CurCommand.IsNotNull())
                {
                    if (text.IsNotNull())
                        text = text + "; ";
                    text += "Komenda: " + CurCommand;
                }
                text = "Budowanie javy [" + Brancz + "]" + Constants.NewLineLinux + text;
                FormMain.UpdateAlertText(Id, text.Replace("; ", Constants.NewLineLinux));
            }

            public void SetData(string str)
            {
                bool setText = false;
                if (str.XMatch("^\\w*:$"))
                {
                    CurCommand = str.Replace(":", "");
                    setText = true;
                }
                string stm = str.GetFirstMatch("^compile(\\w*):$");
                if (buildStm.ContainsIgnoreCase(stm))
                {
                    if (CompileStm != stm)
                    {
                        CompileStm = stm;
                        buildStmIdx++;
                        setText = true;
                    }
                }
                if (str.XMatch("^prepareWebConfigs:"))
                    stm = "Gcm";
                else
                    stm = str.GetFirstMatch("^prepare(\\w*):$");
                
                if (packStm.ContainsIgnoreCase(stm))
                {
                    if (PackStm != stm)
                    {
                        PackStm = stm;
                        packStmIdx++;
                        setText = true;
                    }
                }
                if (setText)
                    SetProgressText();
            }
        }
        private static Dictionary<Process, BudujProcInfo> budowanieProcess = new Dictionary<Process, BudujProcInfo>();


        public static void BuildPack(string brancz, string template, int server, bool clean, bool deploy, bool stopOnError, bool showInfo, bool updateBuildXml, DataRow row)
        {
            if (brancz.IsNull())
                brancz = Setup.Brancze.BranczeTools.ActiveBranch;
            if (brancz.IsNull())
            {
                FormMain.ShowErrorAlert("Przerwanie zadania Budowanie Javy z powodu braku brancza.");
                return;
            }
            JavaDataSet ds = new JavaDataSet();
            ReadBranch(brancz, ds);
            if (template.IsNotNull())
            {
                JavaDataSet templateDs = new JavaDataSet();
                ReadTemplate(templateDs, template);
                ApplyTemplate(ds, templateDs);
            }
            Process p = GlobalTools.CreateCMDProcess(Buduj_Data);
            GlobalTools.ProcessTools.SetEnvVariable(p, brancz);
            BudujProcInfo i = new BudujProcInfo();
            i.SetDataSet(ds);
            i.Row = row;
            i.Id = "JAVA_BUILD_" + BudujId;
            i.StopOnError = stopOnError;
            i.Brancz = brancz;
            i.LogFile = GlobalTools.FilesTools.GetTemplLogFile("Budowanie_JAVY_" + brancz);
            i.ShowInfo = showInfo;
            ("Zadanie budowania javy brancza " + brancz + ", Schemat: " +
                template + ", Server:" + server + "(" +BrowserCache.GetDisplayForValue(Init.InitFormBrowserNames.Setup.Serwery, server).AsString() + ")"+
                Constants.NewLineLinux + Constants.NewLineLinux).WriteToFile(i.LogFile);
            BudujId++;
            if (showInfo)
            {
                FormMain.ShowAlert("Budowanie Javy\n" + brancz, Properties.Resources.burn_java24, new FormMain.AlertInfo(true, i.Id));
            }
            budowanieProcess.Add(p, i);
            p.EchoOff();
            BuildPack(p, ds, clean, brancz, server, deploy, updateBuildXml);
        }

        private static void Buduj_Data(object sender, DataReceivedEventArgs e)
        {
            string str = "";
            str = e.Data.AsString();
            BudujProcInfo info = null;
            if (budowanieProcess.ContainsKey((Process)sender))
                info = budowanieProcess[(Process)sender];
            if (info != null)
            {
                str.AppendToFile(info.LogFile);
                info.SetData(str);
            }
            if (FindError(str))
            {
                if (info != null && info.StopOnError)
                {
                    FormMain.ShowAlert("Zadania Budowanie Javy [" + info.Brancz + "] przerwane z powodu błędu.", FormMain.ErrorImg, new FormMain.AlertInfo(true));
                    Process.Start(info.LogFile);
                    budowanieProcess.Remove((Process)sender);
                    if (info.Row != null && info.Row["STATUS"].AsString() == Zadanie.Statusy.W_Trakcie)
                    {
                        try
                        {
                            if (FormMain.Instance.InvokeRequired)
                            {
                                FormMain.Instance.Invoke(new Action(() =>
                                {
                                    info.Row["STATUS"] = Zadanie.Statusy.Blad;
                                }));
                            }
                            else
                            {
                                info.Row["STATUS"] = Zadanie.Statusy.Blad;
                            }
                        }
                        catch (Exception ex) { ex.Log(); }
                    }
                    try
                    {
                        ((Process)sender).KillProcessTree();
                        ((Process)sender).Dispose();
                    }
                    catch { }
                }
                else
                {
                    if (info != null)
                        info.Error = true;
                }
            }
            if (str.XMatch("^" + INFO_KONIEC_BUDOWANIA))
            {
                if (info != null)
                {
                    if (info.Row != null && info.Row["STATUS"].AsString() == Zadanie.Statusy.W_Trakcie)
                    {
                        string status ;
                        if(info.Error)
                            status = Zadanie.Statusy.ZakonczoneZBledem;
                        else
                            status = Zadanie.Statusy.Zakonczone;
                        try
                        {
                            if (FormMain.Instance.InvokeRequired)
                            {
                                FormMain.Instance.Invoke(new Action(() =>
                                {
                                    info.Row["STATUS"] = status;
                                }));
                            }
                            else
                            {
                                info.Row["STATUS"] = status;
                            }
                        }
                        catch (Exception ex) { ex.Log(); }
                    }
                    
                    FormMain.CloseAlertById(info.Id);
                    Process.Start(info.LogFile);
                    budowanieProcess.Remove((Process)sender);
                    if (info.ShowInfo)
                    {
                        FormMain.ShowInfoAlert("Koniec zadania Budowania Javy [" + info.Brancz + "]");
                    }
                    try
                    {
                        ((Process)sender).KillProcessTree();
                        ((Process)sender).Dispose();
                    }
                    catch { }
                }
            }
        }
        private static void CreateBuildPackProperties(JavaDataSet ds, string branczDir, int serwer)
        {
            string gene = branczDir.TrimEnd('\\') + @"\nd_src\gene";
            string pFile = gene + @"\Pack.properties";
            string bFile = gene + @"\Build.properties";
            string strPack = pFile.ReadFile();
            string strBuild = bFile.ReadFile();
            string sys = "";
            string javaSys;
            DataRow javaSysRow;

            if (strPack.IsNotNull() && strBuild.IsNotNull())
            {
                strBuild = strBuild.XReplace("BUILD_([\\w]*)\\s*=\\s*[YN]", "BUILD_$1=N");
                strPack = strPack.XReplace("PACK_([\\w]*)\\s*=\\s*[YN]", "PACK_$1=N");

                foreach (DataRow r in ds.BUILD.Rows)
                {
                    sys = r["STM"].AsString();
                    javaSys = sys;
                    javaSysRow = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Setup.Apps, sys);
                    if (javaSysRow["STP_APP_IS_JAVA"].AsBool())
                    {
                        if (javaSysRow != null)
                            javaSys = javaSysRow["STP_APP_JAVA_NAME"].AsString();
                        if (javaSys.IsNotNull())
                        {
                            if (r["PAKUJ"].AsBool() || sys == "GCM")
                                strPack = strPack.XReplace("PACK_" + javaSys + "\\s*=\\s*[YN]", "PACK_" + javaSys + "=Y");
                            if (r["BUDUJ"].AsBool())
                                strBuild = strBuild.XReplace("BUILD_" + javaSys + "\\s*=\\s*[YN]", "BUILD_" + javaSys + "=Y");
                        }
                    }
                }
            }

            strPack.TrimStartEnd().WriteToFile(pFile, Encoding.Default);
            DataRow srvRow = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Setup.Serwery, serwer);
            if (srvRow != null)
            {
                string typ = srvRow["STP_SRW_TYP"].AsString();
                string logs = srvRow["STP_SRW_LOGS_DIR"].AsString();
                strBuild = strBuild.XReplace("^app\\.server=(.*)$", "app.server=" + typ, System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                strBuild = strBuild.XReplace("^logs\\.dest=(.*)$", "logs.dest=" + logs, System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            }

            strBuild.TrimStartEnd().WriteToFile(bFile, Encoding.Default);
        }

        public static bool FindError(string str)
        {
            string[] errors = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Work_Group.Java.OznaczenieBledow).XSplit("\n");
            foreach (string s in errors)
            {
                if (s.IsNotNullOrWhiteSpace() && str.XMatch(s.Trim('\r')))
                {
                    return true;
                }
            }
            return false;
        }
        public static bool ShouldAddLog(string str)
        {
            if (FindError(str))
                return true;
            string[] opt = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Work_Group.Java.Wyswietlanie).XSplit("\n");
            foreach (string s in opt)
            {
                if (s.IsNotNullOrWhiteSpace() && str.XMatch(s.Trim('\r')))
                {
                    return true;
                }
            }
            return false;
        }
    }
}
